package com.jxm.linear;

import java.util.Iterator;

/**
 * @Author: jxm
 * @Description: 队列API设计，底层使用单项链表
 * @Date: 2022/6/14 21:55
 * @Version: 1.0
 */
public class Queue<T> implements Iterable<T>{

    //记录首节点
    private Node head;
    //队列中元素个数
    private int N;
    //记录最后一个结点
    private Node last;


    //结点类
    private class Node {
        //存储数据
        private T item;
        //下一个结点
        private Node next;
        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public Queue(){
        this.head = new Node(null,null);
        this.last = null;
        this.N = 0;
    }

    //判断队列是否为空，是返回true，否返回false
    public boolean isEmpty(){
        return N==0;
    }

    //获取队列中元素的个数
    public int size(){
        return N;
    }

    //从队列中拿出一个元素
    public T dequeue(){
        if (isEmpty()) return null;
        //记录第一个元素
        Node oldFirst = head.next;
        head.next = oldFirst.next; //从队头取出一个元素
        //元素个数-1
        N--;
        //因为出队列其实是删除元素，因此如果队列中的元素被删除了，需要重置last=null
        if (isEmpty()) last = null;
        return oldFirst.item;
    }

    //往队列中插入一个元素
    public void enqueue(T t){
        //当前尾节点是null
        if(last == null){
            Node node = new Node(t, null);
            head.next = node;
            last = node;
        }else{
            //当前尾节点不是null
            Node oldLast = last;
            Node node = new Node(t, null);
            last = node;
            oldLast.next = last;
        }

        //元素个数+1
        N++;

    }

    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator{

        private Node n;

        public QIterator(){
            n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }
}
